package com.dao.impl;

import com.dao.WorkingMapper;
import com.entity.Working;
import com.util.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class WorkingDaoImpl implements WorkingMapper {

    SqlSession sqlSession = null;

    @Override
    public List<Working> getListInfos() {
        //定义一个list数组
        List<Working> list = null;

        try {
            //打开数据库连接
            sqlSession = MyBatisUtil.createSqlSession();

            //定义一个list数组
           list = new ArrayList<Working>();
           list = sqlSession.getMapper(WorkingMapper.class).getListInfos();
            System.out.println(list.size());

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            MyBatisUtil.closeSqlSession(sqlSession);
        }
        return list;
    }

    @Override
    public int getListInfoCount(String title) {

        //打开数据库连接
        sqlSession = MyBatisUtil.createSqlSession();

        int count = 0;

        count = sqlSession.getMapper(WorkingMapper.class).getListInfoCount(title);

        return count;
    }

    @Override
    public Working getListInfosById(Integer id) {

        sqlSession = MyBatisUtil.createSqlSession();
        Working working = new Working();

        try {
            working = sqlSession.getMapper(WorkingMapper.class).getListInfosById(id);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            MyBatisUtil.closeSqlSession(sqlSession);
        }

        return working;
    }

    @Override
    public int addInfos(Working working) {

        sqlSession = MyBatisUtil.createSqlSession();
        int result = 0;
        Working working1 = new Working();
        try {
            working1.setTitle(working.getTitle());
            working1.setContent(working.getContent());
            working1.setCreateDate(working.getCreateDate());
            working1.setType(working.getType());
            result = sqlSession.getMapper(WorkingMapper.class).addInfos(working1);
            if (result > 0) {
                sqlSession.commit();
            } else {
                sqlSession.rollback();
            }
        } catch (Exception e) {
            e.printStackTrace();
            sqlSession.rollback();
        } finally {
            MyBatisUtil.closeSqlSession(sqlSession);
        }
        return result;
    }
}
